#include <stdio.h>
#include <stdlib.h>
//list头节点  1.删除时到尾部的 2.便于删除
typedef struct Node{
    int data; 
    struct Node *next;
} Node;

Node *initList() //init_link 
{
    Node *list = (Node *)malloc(sizeof(Node));
    list->data = 0;
    list->next = NULL;
    return list;
}

void headInsert(Node *list, int data) 
{
    Node *node = (Node *)malloc(sizeof(Node));
    node->data = data;
    node->next = list->next;
    list->next = node;
    list->data++;
}
/*
void _taiInsert(Node *list, int data) 
{
    static Node *tail = NULL;//尾指针不需要遍历提高效率 必须先找到尾部
    Node *node = (Node *)malloc(sizeof(Node));
    node->data = data;
    if (!list->next) {
        list->next = node;
    } else {
        tail->next = node;
    }
    tail = node;
}
*/
void tailInsert(Node *list, int data) 
{
    Node *head = list;
    Node *node = (Node *)malloc(sizeof(node));
    node->next = NULL;
    node->data = data;
    while (head->next != NULL) {
        head = head->next;
    }
    head->next = node;
    list->data++;
}
//list头节点  1.删除时到尾部的 2.便于删除
void delete(Node *list, int data)  
{
    Node *pre = list; //头节点便于删除
    Node *cur = list->next;
    while (cur) {//判断条件还有list->data的写法
        if (cur->data == data) {
            pre->next = cur->next;
            break;
        }
        pre = cur;
        cur = cur->next;
    }
    list -> data--;
}

void printList(Node *list)
{
    Node *tmp = list = list->next;
    while (tmp) {
        printf("%d->", tmp->data);
        tmp = tmp->next;
    }
    printf("NULL\n");
}

int main(void) 
{
    Node *list = initList();
    tailInsert(list, 7);
    tailInsert(list, 8);
    tailInsert(list, 9);
    headInsert(list, 1);
    headInsert(list, 2);
    headInsert(list, 3);
    headInsert(list, 4);
    headInsert(list, 5);
    headInsert(list, 6);
    
    //delete(list, 1);
    delete(list, 9);
    delete(list, 4);
    printf("链表的长度\nlist->data: %d\n", list->data);
    printList(list);


    return 0;
}